import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:permission_handler/permission_handler.dart';

class UserMessagerPage extends StatefulWidget {
  const UserMessagerPage({super.key});

  @override
  State<UserMessagerPage> createState() => _UserMessagerPageState();
}

class _UserMessagerPageState extends State<UserMessagerPage> {
  List<dynamic> chatting = [];
  bool showTooltips = false;

  fetchChatting() async {
    var res = await Http.instance.post('/plugin/messager/api/cate');
    if (res.code == 1) {
      chatting = res.data;
    }
    showTooltips = true;
    setState(() {});
  }

  int get unreadCount {
    int total = 0;
    for (var item in chatting) {
      total += item['unRead'] as int;
    }
    return total;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('消息盒子($unreadCount)'),
      ),
      body: UiLifeCycle(
        onRouteDone: () {
          fetchChatting();
        },
        child: Column(
          children: [
            if (showTooltips)
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: UiTheme.spacingX,
                  vertical: 8,
                ),
                color: const Color.fromARGB(255, 239, 251, 239),
                child: Row(
                  children: [
                    UiTap(
                      onTap: () {
                        setState(() {
                          showTooltips = false;
                        });
                      },
                      child: const UiIcon(
                        UiIcons.close,
                        size: 18,
                        color: Colors.black,
                      ),
                    ),
                    const SizedBox(width: 5),
                    const Expanded(
                      child: Text(
                        '开启消息通知，重要提醒不再错过',
                        style: TextStyle(color: Colors.black),
                      ),
                    ),
                    UiTap(
                      onTap: () {
                        openAppSettings();
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 10, vertical: 5),
                        decoration: BoxDecoration(
                          color: UiTheme.primary,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: const Text(
                          '去开启',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            Expanded(
              child: ListView.separated(
                padding: EdgeInsets.only(
                  top: showTooltips ? 0 : UiTheme.toolbarSpacing,
                ),
                itemBuilder: (context, index) {
                  var item = chatting[index];
                  return UiTap(
                    onTap: () async {
                      await App.push(
                          '/messager/chatting?id=${item['id']}&name=${item['name']}');
                      fetchChatting();
                    },
                    child: Container(
                      color: UiTheme(context).panelBackground,
                      padding: const EdgeInsets.symmetric(
                          horizontal: UiTheme.spacingX,
                          vertical: UiTheme.spacingX),
                      child: Row(
                        children: [
                          Badge.count(
                            count: item['unRead'],
                            isLabelVisible: item['unRead'] > 0,
                            child: UiAvatar(
                              size: 60,
                              url: item['image'],
                              radius: UiTheme.boxRadiusX,
                              round: false,
                            ),
                          ),
                          const SizedBox(width: 15),
                          Expanded(
                              child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item['name'],
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  overflow: TextOverflow.ellipsis,
                                  fontSize: 18,
                                ),
                              ),
                              const SizedBox(height: 3),
                              Text(
                                item['intro'],
                                style: const TextStyle(
                                  color: Colors.grey,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ))
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context, index) => const Divider(
                  height: 0,
                  thickness: 0.3,
                  indent: UiTheme.spacingX + 75,
                ),
                itemCount: chatting.length,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
